<template>
  <div>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索与添加区 -->
      <el-row :gutter="20">
        <el-col :span="18">
          <el-input
            v-model.trim="queryInfo.query"
            @keyup.enter.native="queryInfo.query && seachRoleList()"
            placeholder="请输入内容"
            clearable
          >
            <el-button
              @click="queryInfo.query && seachRoleList()"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </el-col>
        <!-- <el-col :span="6">
          <el-button type="primary" @click="addDialogVisiable = true">添加订单</el-button>
        </el-col>-->
      </el-row>

      <!-- 订单列表区 -->
      <el-table :data="orderList" border stripe>
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column label="订单编号" prop="order_number" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column label="订单价格" prop="order_price" align="center" width="90"></el-table-column>
        <el-table-column label="是否付款" prop="pay_status" align="center" width="90">
          <template slot-scope="scope">
            <el-tag
              type="success"
              effect="plain"
              size="mini"
              v-if="scope.row.pay_status === '1'"
            >已付款</el-tag>
            <el-tag type="danger" effect="plain" size="mini" v-else>未付款</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="是否发货" prop="is_send" align="center" width="90"></el-table-column>
        <el-table-column label="下单时间" align="center" width="100">
          <template slot-scope="scope">{{scope.row.create_time | DateFormat}}</template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="130">
          <template slot-scope="scope">
            <!-- 修改按鈕 -->
            <el-tooltip effect="dark" content="修改订单信息" placement="top">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEidtDialog(scope.row.order_id)"
              ></el-button>
            </el-tooltip>
            <!-- 查看物流信息 按鈕 -->
            <el-tooltip effect="dark" content="物流查询" placement="top">
              <el-button
                type="error"
                icon="el-icon-location"
                size="mini"
                @click="showProgressDialog"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 6, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 编辑订单对话框 -->
    <el-dialog
      title="修改订单信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主体区域 -->
      <el-form :model="editForm" ref="editFormRef" label-width="110px">
        <!-- 修改地址 -->
        <el-form-item label="省市区/县：">
          <el-cascader
            v-model="editForm.address1"
            :options="cityData"
            :props="{ expandTrigger: 'hover'}"
          ></el-cascader>
        </el-form-item>
        <!-- 详细地址 -->
        <el-form-item label="详细地址：">
          <el-input v-model.trim="editForm.address2" placeholder="请输入详细地址（不填写不会修改）" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="是否付款：">
          <el-select v-model="editForm.pay_status" placeholder="请选择是否付款">
            <el-option label="是" value="1"></el-option>
            <el-option label="否" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否发货：">
          <el-select v-model="editForm.is_send" placeholder="请选择是否发货">
            <el-option label="是" value="'是'"></el-option>
            <el-option label="否" value="'否'"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editOrderInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 展示物流进度对话框 -->
    <el-dialog title="查看物流进度" :visible.sync="progressDialogVisible" width="50%">
      <!-- 时间线 -->
      <el-timeline>
        <el-timeline-item
          v-for="(activity, index) in progressInfo"
          :key="index"
          :timestamp="activity.time"
        >{{activity.context}}</el-timeline-item>
      </el-timeline>
    </el-dialog>
  </div>
</template>

<script>
import cityData from '../Common/citydata.js'

export default {
  data() {
    return {
      // 获取订单列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        pagesize: 3
      },
      total: 0,
      // 订单列表数据
      orderList: [],
      // 搜索
      orderListRow: [],
      // 控制添加订单对话框的 显示 与 隐藏
      editDialogVisible: false,
      // 添加订单表单的数据
      editForm: {
        address1: [],
        address2: '',
        pay_status: 0,
        is_send: '否'
      },
      // editFormRules: {
      //   address1: [
      //     { required: true, message: '请选择省市区县', trigger: 'blur' }
      //   ],
      //   address2: [
      //     { required: true, message: '请输入详细地址', trigger: 'blur' }
      //   ]
      // },
      // 省市县三联 数据对象
      cityData,
      // 物流进度对话框
      progressDialogVisible: false,
      // 物流进度
      progressInfo: []
    }
  },
  created() {
    this.getOrderList()
  },
  methods: {
    // 获取订单列表
    async getOrderList() {
      const { data } = await this.$axios.get('orders', {
        params: this.queryInfo
      })
      if (data.meta.status !== 200) {
        return this.$message.error('获取订单列表失败')
      }
      this.orderList = data.data.goods
      this.total = data.data.total
      // 也赋值一个给 不变的总列表 ， 便于分页截取
      console.log(data.data)
      this.orderListRow = data.data.goods
    },
    // 监听 pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getOrderList()
      this.orderList = this.orderListRow.slice(0, newSize)
    },
    // 监听 pagesize 最新的页码
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      this.orderList = this.orderListRow.slice(
        (newPage - 1) * this.queryInfo.pagesize,
        newPage * this.queryInfo.pagesize
      )
      this.getOrderList()
    },
    // 订单列表  搜 索事件
    seachRoleList() {
      let arr = []
      // console.log(this.orderListRow)
      this.orderListRow.forEach(val => {
        if (
          val.order_number.includes(this.queryInfo.query) ||
          val.is_send.includes(this.queryInfo.query)
        ) {
          arr.push(val)
        }
      })
      // console.log(arr)
      // 循环后赋值
      this.orderList = arr
    },
    // 监听添加订单 对话框 的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 展示 修改 订单信息 对话框
    async showEidtDialog(id) {
      // 保存点击的 订单 id
      // this.editForm.order_id = id
      // console.log(id)
      const { data } = await this.$axios.get('orders/' + id)
      // console.log(data.data)
      if (data.meta.status !== 200) {
        return this.$message.error('查询订单信息失败！')
      }
      this.editForm = data.data
      this.editDialogVisible = true
    },
    // 监听 修改订单 对话框的事件
    editDialogClosed() {
      //移除表单校验并初始化表单，一般用于添加
      // this.$refs.editFormRef.resetFields()
      //移除表单校验，一般用于修改
      this.$refs.editFormRef.clearValidate()
    },
    // 修改订单信息并提交
    editOrderInfo() {
      // 收获地址
      if (this.editForm.address1) {
        this.editForm.consignee_addr = this.editForm.address1.push(
          this.editForm.address2
        )
      }
      console.log(this.editForm.order_price)
      this.$refs.editFormRef.validate(async valid => {
        // 如果错误 直接 return
        if (!valid) return

        // 发起修改订单信息的 请求
          // {is_send: this.editForm.is_send, pay_status: this.editForm.pay_status, order_price: this.editForm.order_price, order_number: 1}
        const { data } = await this.$axios.put(
          'orders/' + this.editForm.order_id,
          this.editForm
        )
        console.log(data)
        // console.log(data)
        if (data.meta.status !== 201) {
          return this.$message.error('更新订单信息失败！')
        }
        // 隐藏 edit 对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getOrderList()
        // 清空 编辑表单
        this.editForm = {}
        // 提示修改成功
        this.$message.success({ message: '更新订单信息成功！', duration: 1000 })
      })
    },
    // 模拟订单  物流信息
    async showProgressDialog() {
      // 供测试的物流单号：1106975712662
      const { data: res } = await this.$axios.get('/kuaidi/1106975712662')
      if (res.meta.status !== 200) {
        return this.$message.error('获取物流进度失败!')
      }
      this.progressInfo = res.data
      this.progressDialogVisible = true
    }
  }
}
</script>

<style scoped>
.el-cascader {
  width: 100%;
}
</style>